Get around using Object.hasOwnProperty by defining properties you do not want iterate-able with enumerable: false

JavaScript Associative arrays

Whenever you add something to an object, whether it be properties, methods or prototypes, it will be iterate-able (enumerable: true) and show up in a for in loop.
This can cause troubles in associative arrays, and thus many people advocate using Object.hasOwnProperty when iterating over associative arrays.

You can however use Object.defineProperty to set properties to enumerable: false !

var myObject = {};
Object.defineProperty(myObject, "non-iterate-able-property", {
  enumerable: false, 
  value: 42
});

Now lets say you want to make a Class (constructor function) that is a associative array ...

// Create a new MyAssociativeArray and point variable myList to it
var myList = new MyAssociativeArray(); 

myList["foo"] = 1;
mylist["bar"] = 2;

// Iterate over the list
for(var item in myList) {...}

How to add a non-iterate-able, unshared (not a prototype) property to a constructor function:

MyAssociativeArray = function() {
  Object.defineProperty(this, "non-iterate-able-property", {
    enumerable: false, 
	value: 42
  });
}

How to add a non-iterate-able shared method (prototype) to the constructor function:

MyAssociativeArray.prototype.someMethod = function() {...};

// Make it not show up using for in
Object.defineProperty(MyAssociativeArray.prototype, "someMethod", {
  enumerable: false, 
  value: MyAssociativeArray.prototype.someMethod
});

Many people also advocate using Object.keys to convert an object to Array and then Array.forEach to iterate over it.

Object.keys(object).forEach(function(key) {
	console.log(key + "=" + object[key]);
});

While it's faster and less prone to bugs, it gets overly complicated compared to for in, which is also more powerful as you can break the loop.

for(var key in object) {
	console.log(key + "=" + object[key]);
	//if(true) break; // (or return)
}

Written by April 13th 2015.


Follow me via RSS:   RSS https://zäta.com/rss_en.xml (copy to feed-reader)
or Github:   Github https://github.com/Z3TA